package duoxiancheng;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class happyMovie {
    public static void main(String[] args) {
        //可用位置
        List<Integer> available = new ArrayList<Integer>();
        available.add(1);
        available.add(2);
        available.add(3);
        available.add(4);
        available.add(5);

        //顾客一
        List<Integer> seat1 = new ArrayList<Integer>();
        seat1.add(1);
        seat1.add(2);

        //顾客二
        List<Integer> seat2 = new ArrayList<Integer>();
        seat2.add(2);
        seat2.add(3);

        Cinema c = new Cinema(available,"撕葱影院");
        new Thread(new Curtomer(c,seat1),"老张").start();
        new Thread(new Curtomer(c,seat2),"老王").start();
    }
}

//顾客
class Curtomer implements Runnable{
    Cinema cinema;
    List<Integer> seats;

    public Curtomer(Cinema cinema, List<Integer> seats) {
        this.cinema = cinema;
        this.seats = seats;
    }

    @Override
    public void run() {
        synchronized (cinema){
            boolean flag = cinema.bookTickets(seats);
            if (flag){
                System.out.println("出票成功"+Thread.currentThread().getName()+"-<位置为--->"+seats);
            }else {
                System.out.println(Thread.currentThread().getName()+"出票失败，没有票了");
            }
        }
    }
}

//影院
class Cinema{
    List<Integer> available;//可用位置
    String name;//名称

    public Cinema(List<Integer> available, String name) {
        this.available = available;
        this.name = name;
    }

    //购票
    public boolean bookTickets(List<Integer> seats){
        System.out.println("剩余位置为--->"+available);
       List<Integer> copy = new ArrayList<Integer>();
       copy.addAll(available);

       //相减
        copy.removeAll(seats);
        //判断大小
        if(available.size()-copy.size()!=seats.size()){//失败了
            return false;
        }else{//成功，把available指向copy
            available = copy;
        }
        return true;
    }
}
